import ButtonGroup, { Button } from "@/components/ButtonGroup";
import styles from "./style.scss";
import { Image, View } from "@tarojs/components";
import Card from "@/components/Card";
import { useEffect, useState } from "react";
import SearchBar from "@/components/SearchBar";
import { Checkbox } from "@nutui/nutui-react-taro";
import { useRequest } from "taro-hooks";
import { getMaterialList } from "@/services/Material";
import { useFamilyStore } from "@/model";
import { getImgUrl } from "@/utils";

export default (props) => {
  const { onConfirm, onClose, value, open } = props;
  const { family } = useFamilyStore();

  const [searchParams, setSearchParams] = useState({
    familyId: family?.id,
    materialClassificationId: "1772277837774557185",
  });
  const [selectItem, setSelectItem] = useState(null);

  const { data: list } = useRequest(() => getMaterialList(searchParams), {
    refreshDeps: [searchParams],
  });
  const changeSearchParams = (v) => {
    setSearchParams({
      ...searchParams,
      ...v,
    });
  };
  useEffect(() => {
    setSelectItem(value);
  }, [value]);
  return (
    <View className={styles.container}>
      <View
        className={styles.selectPanel}
        style={{ display: open ? "flex" : "none" }}
      >
        <View className={styles.listWrap}>
          <View>
            <SearchBar
              onSearch={(v) => {
                changeSearchParams({
                  name: v,
                });
              }}
            />
          </View>

          <View className={styles.list}>
            {list?.list?.map?.((item) => {
              return (
                <Card key={item.id}>
                  <View className={styles.card}>
                    <Image
                      src={getImgUrl(item.imgUrl)}
                      className={styles.icon}
                    />
                    <View className={styles.middle}>
                      <View className={styles.name}>{item.name}</View>
                    </View>
                    <Checkbox
                      checked={selectItem?.id === item.id}
                      className={styles.check}
                      onChange={(e) => {
                        if (e) {
                          setSelectItem(item);
                        } else {
                          setSelectItem(null);
                        }
                      }}
                    />
                  </View>
                </Card>
              );
            })}
          </View>
        </View>
        <ButtonGroup>
          <Button onClick={() => onClose()}>取消</Button>
          <Button
            type="primary"
            onClick={() => {
              onConfirm(selectItem);
            }}
          >
            确定
          </Button>
        </ButtonGroup>
      </View>
    </View>
  );
};
